package sk.tramtatiri.pages.users;

import java.util.Calendar;
import java.util.Date;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import sk.tramtatiri.MySession;
import sk.tramtatiri.data.dao.interfaces.FoodDao;
import sk.tramtatiri.data.dao.interfaces.InOutHelperDao;
import sk.tramtatiri.data.dao.interfaces.UserDao;
import sk.tramtatiri.data.dao.interfaces.UserFoodDao;
import sk.tramtatiri.data.dao.interfaces.UserRecipeDao;
import sk.tramtatiri.data.dataobjects.Food;
import sk.tramtatiri.data.dataobjects.InOutHelper;
import sk.tramtatiri.data.dataobjects.UserFood;
import sk.tramtatiri.data.dataobjects.UserRecipe;

public class FoodCreatePanel extends Panel{
	private static final long serialVersionUID = -1510400663376934203L;

	@SpringBean
	private FoodDao foodDao;
	@SpringBean
	private UserFoodDao userFoodDao;
	@SpringBean
	private UserDao userDao;
	@SpringBean
	private UserRecipeDao userRecipeDao;
	@SpringBean
	private InOutHelperDao inOutHelperDao;
	
	public FoodCreatePanel(String id) {
		super(id);
		
		FeedbackPanel feedback = new FeedbackPanel("feedback");
		feedback.setOutputMarkupId(true);
		add(feedback);
		
		final TextField<String> foodName = new TextField<String>("foodName", Model.of(""));
		foodName.setRequired(true);

		final TextField<String> foodCalories = new TextField<String>("foodCalories", Model.of(""));
		foodCalories.setRequired(true);
		final TextField<String> foodSaccharides = new TextField<String>("foodSaccharides", Model.of(""));
		foodSaccharides.setRequired(true);
		final TextField<String> foodFats = new TextField<String>("foodFats", Model.of(""));
		foodFats.setRequired(true);
		final TextField<String> foodProteins = new TextField<String>("foodProteins", Model.of(""));
		foodProteins.setRequired(true);
		final TextField<String> foodWeight = new TextField<String>("foodWeight", Model.of(""));
		foodWeight.setRequired(true);
		
		final TextArea<String> foodDescription = new TextArea<String>("foodDescription", Model.of("[Zadajte postup pripravy]"));
		foodDescription.setRequired(true);
		
		final Form<?> form = new Form<Void>("formFoodCreate");
		form.add(new Button("subButton"){
			private static final long serialVersionUID = -2275135888755634649L;

			@Override
			public void onSubmit() {
				String name = foodName.getDefaultModelObjectAsString().trim();
				String scalories = foodCalories.getDefaultModelObjectAsString();
				String sfats = foodFats.getDefaultModelObjectAsString();
				String sproteins = foodProteins.getDefaultModelObjectAsString();
				String ssaccharides = foodSaccharides.getDefaultModelObjectAsString();
				String sweight = foodWeight.getDefaultModelObjectAsString();
				if(foodDao.findName(name) == null && scalories.matches("\\d+") && sweight.matches("\\d+")
						 && sfats.matches("\\d+") && sproteins.matches("\\d+") && ssaccharides.matches("\\d+")){
					
					Food food = new Food();
					
					int calories = Integer.valueOf(scalories);
					int fats = Integer.valueOf(sfats);
					int proteins = Integer.valueOf(sproteins);
					int saccharides = Integer.valueOf(ssaccharides);
					int weight = Integer.valueOf(sweight);
					
					float times = (float)weight / 100;
					
					calories = Math.round((float)calories/times);
					fats = Math.round((float)fats/times);
					proteins = Math.round((float)proteins/times);
					saccharides = Math.round((float)saccharides/times);
					
					if(weight == 0){
						calories = 0;
						fats = 0;
						proteins = 0;
						saccharides = 0;
					}
					
					if(calories == 0 || Integer.valueOf(fats) == 0 || Integer.valueOf(proteins) == 0 ||
							Integer.valueOf(saccharides) == 0 || foodDescription.getDefaultModelObjectAsString().equals("")){
						food.setAllValues(false);
					}else {
						food.setAllValues(true);
					}
					food.setCalories(Integer.valueOf(calories));
					food.setCreatorID(((MySession)getSession()).getUserID());
					food.setDescription(foodDescription.getDefaultModelObjectAsString());
					food.setFats(Integer.valueOf(fats));
					food.setName(name);
					food.setProteins(Integer.valueOf(proteins));
					food.setRating(0);
					food.setSaccharides(Integer.valueOf(saccharides));
					foodDao.save(food);
					
					CheckBox box = (CheckBox)form.get("foodCheck");
					if((Boolean) box.getDefaultModelObject()){
						UserFood userFood = new UserFood();
						
						Calendar cal = Calendar.getInstance();
						cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
								cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
						
						userFood.setDate(new Date(cal.getTimeInMillis()));
						userFood.setUser(userDao.load(((MySession) getSession())
								.getUserID()));
						userFood.setUserId(((MySession) getSession())
								.getUserID());
						//TODO WTF
						userFood.setQuantity(Integer.valueOf(sweight));
						userFood.setTotalCalories(Integer.valueOf(scalories));
						userFood.setFood(food);
						long idFood = foodDao.findName(name).getId();
						userFood.setFoodId(idFood);
						userFoodDao.save(userFood);
						
						int totalTodayRec = userRecipeDao.sumUserToday(((MySession)getSession()).getUserID());
						int totalTodayFood = userFoodDao.sumUserToday(((MySession)getSession()).getUserID());
						InOutHelper todayHelper = inOutHelperDao.findByUserToday(((MySession)getSession()).getUserID());
						if(todayHelper!=null)
							todayHelper.setCaloriesIn(totalTodayRec+totalTodayFood);
						else {
							InOutHelper newHelper = new InOutHelper();
							newHelper.setDate(new Date(cal.getTimeInMillis()));
							newHelper.setCaloriesIn(totalTodayRec+totalTodayFood);
							newHelper.setUsrid(((MySession)getSession()).getUserID());
							inOutHelperDao.save(newHelper);
						}
						
						info("Potravina bola vytvorena a pridana ku zjedenym");
						
						userDao.load(((MySession) getSession()).getUserID())
								.getFoods().add(userFood);
						foodDao.load(idFood).getUsers().add(userFood);
					}	
					
					info("Potravina bola vytvorena");
					RequestCycle rc = RequestCycle.get();
					rc.setResponsePage(FoodsPage.class);
				} else {
					//TODO cerveny text nazvu potraviny
					error("Zadana potravina uz existuje, pripadne zadane hodnoty nie su povolene");
				}
			}
		});
		
		form.add(new CheckBox("foodCheck", new Model<Boolean>(true)));
		
		add(form);
		
		form.add(foodName);
		form.add(foodCalories);
		form.add(foodFats);
		form.add(foodProteins);
		form.add(foodSaccharides);
		form.add(foodDescription);
		form.add(foodWeight);
	}
}
